#include "stdafx.h"
#include "serwer.hpp"
#include <cstdlib>
//#include <boost/thread.hpp>
#include <boost/bind.hpp>
#include <boost/smart_ptr.hpp>
#include <iostream>
#include "wyjatki.h"

//namespace boost { struct thread::dummy {}; }

using namespace boost;
using namespace boost::asio;
using namespace System;
using namespace System::Threading;

Socket::Socket(ip::tcp::socket* socket) {
   this->socket = socket;
}

SerwerTCP::SerwerTCP(io_service& io_service, short port)
   : io_service_(io_service),
     socket_(io_service),
     acceptor_(io_service,
	       ip::tcp::endpoint(ip::tcp::v4(),port)) {
      
}

std::string SerwerTCP::odbierz(shared_ptr<ip::tcp::socket> sock) {
  
      /*boost::asio::streambuf b;
	boost::asio::read_until(*sock, b, ']');
	std::istream is(&b);
	std::string line;
	std::getline(is, line); 
	std::cout << line << std::endl;
	boost::asio::write(*sock, boost::asio::buffer(line.c_str(), line.size()));*/
	  //char data[512];

      //boost::system::error_code error;
      //size_t length = sock->read_some(boost::asio::buffer(data), error);
      

      //boost::asio::write(*sock, boost::asio::buffer(data, length));
    //}

      system::error_code error;
      asio::streambuf b;
      //size_t dlugosc = read_until(*sock,buffer(dane), error);
	  //size_t length = sock->read_some(b, error);
      read_until(*sock, b, "<", error);
      std::istream is(&b);
      std::string ramka;
	  
      //boost::asio::write(*sock, boost::asio::buffer(data, length));
      
      if(error == error::eof) {
	 //return ramka; //polaczenie zamknieto poprawnie, i zwracamy pusta ramke
	 //mozna by zamiast zwrotu pustej ramki rzucic wyjatkiem w sumie
	 throw Wyjatek("Polaczenie zamknieto prawidlowo");

      }
      else if(error) { 
		  throw Wyjatek("Polaczenie zamknieto nieprawidlowo");
	 //throw system::system_error(error); //polaczenia nie zamknieto poprawnie
	  }
      
      //write(*sock, buffer(dane, dlugosc));
      std::getline(is, ramka);
	  std::cout << ramka << std::endl;
      //write(*sock,buffer(ramka.c_str(),ramka.size()));
      return ramka;
      //return std::string();
}

shared_ptr<ip::tcp::socket> SerwerTCP::akceptuj() {   
   //ip::tcp::socket* sock = new ip::tcp::socket(io_service_);
	Console::WriteLine("Ktos tu jednak nasluchuje");
   shared_ptr<ip::tcp::socket> sock(new ip::tcp::socket(io_service_));
   acceptor_.accept(*sock);   
   return sock;
}

void SerwerTCP::wyslij(shared_ptr<ip::tcp::socket> sock, std::string dane) {
   write(*sock, buffer(dane.c_str(), dane.size()));
}
